#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "dnspacket.h"

int main(void)
{
    int cli_sockfd;
    int len;
    socklen_t addrlen;

    char seraddr[] = "202.103.24.68";
    struct sockaddr_in cli_addr;
    unsigned char buffer[256];
    
    int i = 0;
    
    CDnsPacket dns_send_pack;
    CDnsPacket dns_recv_pack;

    cli_sockfd=socket(AF_INET, SOCK_DGRAM, 0);
    if ( cli_sockfd < 0 )
    {
        printf("socket fail!\n");
    }

    addrlen = sizeof(struct sockaddr_in);
    bzero(&cli_addr,addrlen);
    cli_addr.sin_family = AF_INET;
    cli_addr.sin_addr.s_addr = inet_addr(seraddr);
    cli_addr.sin_port = htons(53);
    bzero(buffer, sizeof(buffer));
    
    buffer[0] = 0x73;
    buffer[1] = 0xc7;

    buffer[2] = 0x01;
    buffer[3] = 0x00;

    buffer[4] = 0x00;
    buffer[5] = 0x01;
    
    buffer[6] = 0x00;
    buffer[7] = 0x00;
    
    buffer[8] = 0x00;
    buffer[9] = 0x00;

    buffer[10] = 0x00;
    buffer[11] = 0x00;

    //----- queries -----
    buffer[12] = 0x03;
    buffer[13] = 0x77;
    buffer[14] = 0x77;
    buffer[15] = 0x77;
    buffer[16] = 0x04;
    buffer[17] = 0x73;
    buffer[18] = 0x69;
    buffer[19] = 0x6e;
    buffer[20] = 0x61;
    buffer[21] = 0x03;
    buffer[22] = 0x63;
    buffer[23] = 0x6f;
    buffer[24] = 0x6d;
    buffer[25] = 0x02;
    buffer[26] = 0x63;
    buffer[27] = 0x6e;
    buffer[28] = 0x00;
    
    buffer[29] = 0x00;
    buffer[30] = 0x01;
    
    buffer[31] = 0x00;
    buffer[32] = 0x01;

    dns_send_pack.InitData(buffer, 33);
    sendto(cli_sockfd, buffer, 33, 0, (struct sockaddr*)&cli_addr, addrlen);
#ifdef DEBUG_PRINT  
    dns_send_pack.DebugPrintDnsInfo();
#endif

    bzero(buffer, sizeof(buffer));
    len = recvfrom(cli_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&cli_addr, &addrlen);

    for (i=0; i<len; i++)
    {
        if ( i % 16 == 0 )
        {
            printf("\n");
        }
        printf("%02x ", buffer[i]);
    }
    printf("\n");
    
    
    dns_recv_pack.InitData(buffer, len);
#ifdef DEBUG_PRINT    
    dns_recv_pack.DebugPrintDnsInfo();
#endif
    
    close(cli_sockfd);

    return 0;
}
